package com.fast.ThreadPoolFactory;

import cn.hutool.core.thread.NamedThreadFactory;

import java.util.concurrent.*;

/**
 * CompletableFuture
 * 主要是用于多任务组合，任务执行成功，然后执行下一步
 * <p>
 * anyOf   有一个执行完，就获取返回结果，进行下一步操作
 * allOf   都执行完,再获取执行结果进行下一步操作
 *
 * @author hjw
 * @since 2022年07月17日 18:13:00
 */
public class CF6_allOf_anyOf {

    public static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors() * 2,
            Runtime.getRuntime().availableProcessors() * 2,
            10,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(300),
            new NamedThreadFactory("core_thread_pool_", true),
            new ThreadPoolExecutor.AbortPolicy()
    );

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始了-----------");


        CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> {
            System.out.println("A线程" + Thread.currentThread().getName() + "--------把任务A执行完了");
            return "hello";
        }, threadPoolExecutor);

        CompletableFuture<String> futureB = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("B线程" + Thread.currentThread().getName() + "--------把任务B执行完了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "world";
        }, threadPoolExecutor);

        CompletableFuture<String> futureC = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("C线程" + Thread.currentThread().getName() + "--------把任务C执行完了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "world";
        }, threadPoolExecutor);

        //1.有一个执行完，anyOf.get()获取的最先执行完的那个
        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(futureA, futureB, futureC);
        System.out.println("anyOf返回值 =" + anyOf.get());
        System.out.println("主线程结束了--------------");

        //2.都执行完
        CompletableFuture<Void> allOf = CompletableFuture.allOf(futureA, futureB, futureC);
        allOf.get();//主要用于阻塞进程，等待三个都执行完
        System.out.println("allOf返回值 = " + futureA.get() + futureB.get() + futureC.get());


    }
}
